#include"proto.h"
#include"network.h"
#include"recvF.h"
#include<unistd.h>
#include<string.h>

void sendCmd(int sock, pTCB cmd)
{
	send(sock, cmd, sizeof(TCB), 0);
}

void prepareTransfer(char* filename, size_t fnlen, int offset, int dataLen, pTCB cmd)
{
	cmd->cmd = 1;
	
	
	if (fnlen >= MAX_FILE_NAME_LEN)
	{
		printf("File name is too long\n");
		return;
	}
	memcpy(&(cmd->fileName), filename, fnlen);
	cmd->fileName[fnlen] = '\0';

	cmd->offset = offset;
	cmd->dataLen = dataLen;
}

/*
 * You need to close the file outside of this function!!!
 */
void getFileSeg(int sock, FILE* fout, pTCB cmd)
{
	char buf[BUFF_SIZE];
	int recvEd = 0;
	ssize_t recvLen;
	if (fout <=0)
	{
		printf("Dest file is not open yet\n");
		return;
	}
	sendCmd(sock, cmd);
	while((recvLen=recv(sock, buf, BUFF_SIZE, 0))>0)
	{
		fwrite(buf, recvLen, 1, fout);
		printf("%dB recv\n", recvLen);
		recvEd+=recvLen;
		if (recvEd >= cmd->dataLen)
			break;
	}
}

int getFileLen(int sock, char* filename,size_t fnlen)
{	
	char buf[BUFF_SIZE];
	TCB cmd;
	cmd.cmd = 0;

	if (fnlen > MAX_FILE_NAME_LEN-1)
	{
		printf("File name is too long\n");
		return -1;
	}
	int tmp;
	memcpy(&(cmd.fileName), filename, fnlen);
	cmd.fileName[fnlen]='\0';
	send(sock, &cmd, sizeof(cmd), 0);
	printf("%d\n", recv(sock, &tmp, sizeof(tmp), 0));
	return tmp;
}
